<script lang="ts" setup>
import {useMonacoEditor} from '/@/hooks/use-monaco-editor'

const props = withDefaults(
    defineProps<{
      id?: string,
      width?: string | number
      height?: string | number
      language?: string
      editorOption?: Object
      modelValue: string
    }>(),
    {
      id: 'monaco-editor',
      width: '100%',
      height: '30vh',
      language: 'java',
      editorOption: () => ({
        minimap: {
          enabled: false
        }
      }),
      modelValue: '',
    }
)

const emits = defineEmits<{
  (e: 'update:modelValue', val: string): void
}>()

const monacoEditorStyle = computed(() => {
  return {
    width: typeof props.width === 'string' ? props.width : props.width + 'px',
    height: typeof props.height === 'string' ? props.height : props.height + 'px',
  }
})

const {monacoEditorRef, createEditor, updateVal, updateOptions, getEditor} = useMonacoEditor(props.language)


onMounted(() => {
  nextTick(() => {
    monacoEditorRef.value = document.getElementById(props.id)
    const monacoEditor = createEditor(props.editorOption)
    updateMonacoVal(props.modelValue)
    monacoEditor?.onDidChangeModelContent(() => {
      emits('update:modelValue', monacoEditor!.getValue())
    })
  })
})

watch(
    () => props.modelValue,
    () => {
      updateMonacoVal(props.modelValue)
    }
)

function updateMonacoVal(val: string) {
  if (val !== getEditor()?.getValue()) {
    updateVal(val)
  }
}

defineExpose({updateOptions})
</script>

<template>
  <div :id="id" ref="monacoEditorRef" :style="monacoEditorStyle">
  </div>
</template>
